package com.it.labservice.controller;

import com.alibaba.excel.EasyExcel;
import com.it.labservice.entity.*;
import com.it.labservice.repository.*;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

@RestController
@RequestMapping("/api")
public class ApiController {
    
    @Autowired
    private CollegeRepository collegeRepository;
    
    @Autowired
    private TermRepository termRepository;
    
    @Autowired
    private LaboratoryRepository laboratoryRepository;
    
    @Autowired
    private UserRepository userRepository;
    
    @Autowired
    private SafetyCheckRepository safetyCheckRepository;
    
    // 获取管理员数据API
    @GetMapping("/managers")
    public ResponseEntity<?> getManagers(HttpSession session) {
        User currentUser = (User) session.getAttribute("currentUser");
        if (currentUser == null || !User.UserRole.ADMIN.equals(currentUser.getRole())) {
            return ResponseEntity.ok(new HashMap<String, Object>() {{
                put("success", false);
                put("message", "权限不足");
            }});
        }
        
        try {
            var managers = userRepository.findByRole(User.UserRole.LAB_MANAGER);
            var result = managers.stream().map(user -> {
                Map<String, Object> userMap = new HashMap<>();
                userMap.put("id", user.getId());
                userMap.put("name", user.getName());
                userMap.put("username", user.getUsername());
                userMap.put("college", user.getCollege() != null ? user.getCollege().getName() : "无");
                userMap.put("contactInfo", user.getContactInfo() != null ? user.getContactInfo() : "无");
                return userMap;
            }).toList();
            
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            return ResponseEntity.ok(new HashMap<String, Object>() {{
                put("success", false);
                put("message", "获取管理员数据失败：" + e.getMessage());
            }});
        }
    }
    
    // 学院管理API
    @PostMapping("/colleges")
    public ResponseEntity<Map<String, Object>> createCollege(@RequestParam String name, HttpSession session) {
        Map<String, Object> response = new HashMap<>();
        
        User currentUser = (User) session.getAttribute("currentUser");
        if (currentUser == null || !User.UserRole.ADMIN.equals(currentUser.getRole())) {
            response.put("success", false);
            response.put("message", "权限不足");
            return ResponseEntity.ok(response);
        }
        
        try {
            College college = new College();
            college.setName(name);
            college.setCreateTime(LocalDateTime.now());
            collegeRepository.save(college);
            
            response.put("success", true);
            response.put("message", "学院添加成功");
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "添加失败：" + e.getMessage());
        }
        
        return ResponseEntity.ok(response);
    }
    
    @PutMapping("/colleges/{id}")
    public ResponseEntity<Map<String, Object>> updateCollege(@PathVariable Long id, @RequestParam String name, HttpSession session) {
        Map<String, Object> response = new HashMap<>();
        
        User currentUser = (User) session.getAttribute("currentUser");
        if (currentUser == null || !User.UserRole.ADMIN.equals(currentUser.getRole())) {
            response.put("success", false);
            response.put("message", "权限不足");
            return ResponseEntity.ok(response);
        }
        
        try {
            Optional<College> collegeOpt = collegeRepository.findById(id);
            if (collegeOpt.isPresent()) {
                College college = collegeOpt.get();
                college.setName(name);
                collegeRepository.save(college);
                
                response.put("success", true);
                response.put("message", "学院更新成功");
            } else {
                response.put("success", false);
                response.put("message", "学院不存在");
            }
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "更新失败：" + e.getMessage());
        }
        
        return ResponseEntity.ok(response);
    }
    
    @DeleteMapping("/colleges/{id}")
    public ResponseEntity<Map<String, Object>> deleteCollege(@PathVariable Long id, HttpSession session) {
        Map<String, Object> response = new HashMap<>();
        
        User currentUser = (User) session.getAttribute("currentUser");
        if (currentUser == null || !User.UserRole.ADMIN.equals(currentUser.getRole())) {
            response.put("success", false);
            response.put("message", "权限不足");
            return ResponseEntity.ok(response);
        }
        
        try {
            Optional<College> collegeOpt = collegeRepository.findById(id);
            if (collegeOpt.isPresent()) {
                College college = collegeOpt.get();
                if (college.getLaboratories() != null && !college.getLaboratories().isEmpty()) {
                    response.put("success", false);
                    response.put("message", "该学院下还有实验室，无法删除");
                } else {
                    collegeRepository.delete(college);
                    response.put("success", true);
                    response.put("message", "学院删除成功");
                }
            } else {
                response.put("success", false);
                response.put("message", "学院不存在");
            }
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "删除失败：" + e.getMessage());
        }
        
        return ResponseEntity.ok(response);
    }
    
    // 学期管理API
    @PostMapping("/terms")
    public ResponseEntity<Map<String, Object>> createTerm(@RequestParam String name, 
                                                         @RequestParam String startDate,
                                                         @RequestParam String endDate,
                                                         HttpSession session) {
        Map<String, Object> response = new HashMap<>();
        
        User currentUser = (User) session.getAttribute("currentUser");
        if (currentUser == null || !User.UserRole.ADMIN.equals(currentUser.getRole())) {
            response.put("success", false);
            response.put("message", "权限不足");
            return ResponseEntity.ok(response);
        }
        
        try {
            Term term = new Term();
            term.setName(name);
            term.setStartDate(LocalDate.parse(startDate));
            term.setEndDate(LocalDate.parse(endDate));
            term.setStatus(Term.TermStatus.FUTURE);
            termRepository.save(term);
            
            response.put("success", true);
            response.put("message", "学期添加成功");
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "添加失败：" + e.getMessage());
        }
        
        return ResponseEntity.ok(response);
    }
    
    @PutMapping("/terms/{id}")
    public ResponseEntity<Map<String, Object>> updateTerm(@PathVariable Long id,
                                                         @RequestParam String name,
                                                         @RequestParam String startDate,
                                                         @RequestParam String endDate,
                                                         HttpSession session) {
        Map<String, Object> response = new HashMap<>();
        
        User currentUser = (User) session.getAttribute("currentUser");
        if (currentUser == null || !User.UserRole.ADMIN.equals(currentUser.getRole())) {
            response.put("success", false);
            response.put("message", "权限不足");
            return ResponseEntity.ok(response);
        }
        
        try {
            Optional<Term> termOpt = termRepository.findById(id);
            if (termOpt.isPresent()) {
                Term term = termOpt.get();
                term.setName(name);
                term.setStartDate(LocalDate.parse(startDate));
                term.setEndDate(LocalDate.parse(endDate));
                termRepository.save(term);
                
                response.put("success", true);
                response.put("message", "学期更新成功");
            } else {
                response.put("success", false);
                response.put("message", "学期不存在");
            }
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "更新失败：" + e.getMessage());
        }
        
        return ResponseEntity.ok(response);
    }
    
    @DeleteMapping("/terms/{id}")
    public ResponseEntity<Map<String, Object>> deleteTerm(@PathVariable Long id, HttpSession session) {
        Map<String, Object> response = new HashMap<>();
        
        User currentUser = (User) session.getAttribute("currentUser");
        if (currentUser == null || !User.UserRole.ADMIN.equals(currentUser.getRole())) {
            response.put("success", false);
            response.put("message", "权限不足");
            return ResponseEntity.ok(response);
        }
        
        try {
            Optional<Term> termOpt = termRepository.findById(id);
            if (termOpt.isPresent()) {
                Term term = termOpt.get();
                if (Term.TermStatus.CURRENT.equals(term.getStatus())) {
                    response.put("success", false);
                    response.put("message", "当前学期无法删除");
                } else {
                    termRepository.delete(term);
                    response.put("success", true);
                    response.put("message", "学期删除成功");
                }
            } else {
                response.put("success", false);
                response.put("message", "学期不存在");
            }
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "删除失败：" + e.getMessage());
        }
        
        return ResponseEntity.ok(response);
    }
    
    @PostMapping("/terms/{id}/activate")
    public ResponseEntity<Map<String, Object>> activateTerm(@PathVariable Long id, HttpSession session) {
        Map<String, Object> response = new HashMap<>();
        
        User currentUser = (User) session.getAttribute("currentUser");
        if (currentUser == null || !User.UserRole.ADMIN.equals(currentUser.getRole())) {
            response.put("success", false);
            response.put("message", "权限不足");
            return ResponseEntity.ok(response);
        }
        
        try {
            Optional<Term> termOpt = termRepository.findById(id);
            if (termOpt.isPresent()) {
                // 先将所有学期设为非当前状态
                termRepository.findAll().forEach(term -> {
                    if (Term.TermStatus.CURRENT.equals(term.getStatus())) {
                        term.setStatus(Term.TermStatus.ENDED);
                        termRepository.save(term);
                    }
                });
                
                // 激活指定学期
                Term term = termOpt.get();
                term.setStatus(Term.TermStatus.CURRENT);
                termRepository.save(term);
                
                response.put("success", true);
                response.put("message", "学期激活成功");
            } else {
                response.put("success", false);
                response.put("message", "学期不存在");
            }
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "激活失败：" + e.getMessage());
        }
        
        return ResponseEntity.ok(response);
    }
    
    @PostMapping("/terms/{id}/deactivate")
    public ResponseEntity<Map<String, Object>> deactivateTerm(@PathVariable Long id, HttpSession session) {
        Map<String, Object> response = new HashMap<>();
        
        User currentUser = (User) session.getAttribute("currentUser");
        if (currentUser == null || !User.UserRole.ADMIN.equals(currentUser.getRole())) {
            response.put("success", false);
            response.put("message", "权限不足");
            return ResponseEntity.ok(response);
        }
        
        try {
            Optional<Term> termOpt = termRepository.findById(id);
            if (termOpt.isPresent()) {
                Term term = termOpt.get();
                term.setStatus(Term.TermStatus.ENDED);
                termRepository.save(term);
                
                response.put("success", true);
                response.put("message", "学期停用成功");
            } else {
                response.put("success", false);
                response.put("message", "学期不存在");
            }
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "停用失败：" + e.getMessage());
        }
        
        return ResponseEntity.ok(response);
    }
    
    // 实验室管理API
    @PostMapping("/laboratories")
    public ResponseEntity<Map<String, Object>> createLaboratory(@RequestParam String name,
                                                               @RequestParam Long collegeId,
                                                               HttpSession session) {
        Map<String, Object> response = new HashMap<>();
        
        User currentUser = (User) session.getAttribute("currentUser");
        if (currentUser == null || !User.UserRole.ADMIN.equals(currentUser.getRole())) {
            response.put("success", false);
            response.put("message", "权限不足");
            return ResponseEntity.ok(response);
        }
        
        try {
            Optional<College> collegeOpt = collegeRepository.findById(collegeId);
            if (collegeOpt.isPresent()) {
                Laboratory laboratory = new Laboratory();
                laboratory.setName(name);
                laboratory.setCollege(collegeOpt.get());
                laboratoryRepository.save(laboratory);
                
                response.put("success", true);
                response.put("message", "实验室添加成功");
            } else {
                response.put("success", false);
                response.put("message", "学院不存在");
            }
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "添加失败：" + e.getMessage());
        }
        
        return ResponseEntity.ok(response);
    }
    
    @PutMapping("/laboratories/{id}")
    public ResponseEntity<Map<String, Object>> updateLaboratory(@PathVariable Long id,
                                                               @RequestParam String name,
                                                               @RequestParam Long collegeId,
                                                               HttpSession session) {
        Map<String, Object> response = new HashMap<>();
        
        User currentUser = (User) session.getAttribute("currentUser");
        if (currentUser == null || !User.UserRole.ADMIN.equals(currentUser.getRole())) {
            response.put("success", false);
            response.put("message", "权限不足");
            return ResponseEntity.ok(response);
        }
        
        try {
            Optional<Laboratory> labOpt = laboratoryRepository.findById(id);
            Optional<College> collegeOpt = collegeRepository.findById(collegeId);
            
            if (labOpt.isPresent() && collegeOpt.isPresent()) {
                Laboratory laboratory = labOpt.get();
                laboratory.setName(name);
                laboratory.setCollege(collegeOpt.get());
                laboratoryRepository.save(laboratory);
                
                response.put("success", true);
                response.put("message", "实验室更新成功");
            } else {
                response.put("success", false);
                response.put("message", "实验室或学院不存在");
            }
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "更新失败：" + e.getMessage());
        }
        
        return ResponseEntity.ok(response);
    }
    
    @DeleteMapping("/laboratories/{id}")
    public ResponseEntity<Map<String, Object>> deleteLaboratory(@PathVariable Long id, HttpSession session) {
        Map<String, Object> response = new HashMap<>();
        
        User currentUser = (User) session.getAttribute("currentUser");
        if (currentUser == null || !User.UserRole.ADMIN.equals(currentUser.getRole())) {
            response.put("success", false);
            response.put("message", "权限不足");
            return ResponseEntity.ok(response);
        }
        
        try {
            Optional<Laboratory> labOpt = laboratoryRepository.findById(id);
            if (labOpt.isPresent()) {
                Laboratory laboratory = labOpt.get();
                // 检查是否有安全检查记录
                if (laboratory.getSafetyChecks() != null && !laboratory.getSafetyChecks().isEmpty()) {
                    response.put("success", false);
                    response.put("message", "该实验室有安全检查记录，无法删除");
                } else {
                    laboratoryRepository.delete(laboratory);
                    response.put("success", true);
                    response.put("message", "实验室删除成功");
                }
            } else {
                response.put("success", false);
                response.put("message", "实验室不存在");
            }
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "删除失败：" + e.getMessage());
        }
        
        return ResponseEntity.ok(response);
    }
    
    // 用户管理API
    @PostMapping("/users")
    public ResponseEntity<Map<String, Object>> createUser(@RequestParam String username,
                                                         @RequestParam String name,
                                                         @RequestParam String role,
                                                         @RequestParam(required = false) Long collegeId,
                                                         HttpSession session) {
        Map<String, Object> response = new HashMap<>();
        
        User currentUser = (User) session.getAttribute("currentUser");
        if (currentUser == null || !User.UserRole.ADMIN.equals(currentUser.getRole())) {
            response.put("success", false);
            response.put("message", "权限不足");
            return ResponseEntity.ok(response);
        }
        
        try {
            // 检查用户名是否已存在
            if (userRepository.findByUsername(username) != null) {
                response.put("success", false);
                response.put("message", "用户名已存在");
                return ResponseEntity.ok(response);
            }
            
            User user = new User();
            user.setUsername(username);
            user.setName(name);
            user.setPassword("123456"); // 默认密码
            user.setRole(User.UserRole.valueOf(role));
            user.setIsActive(true);
            
            if (collegeId != null) {
                Optional<College> collegeOpt = collegeRepository.findById(collegeId);
                if (collegeOpt.isPresent()) {
                    user.setCollege(collegeOpt.get());
                }
            }
            
            userRepository.save(user);
            
            response.put("success", true);
            response.put("message", "用户添加成功");
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "添加失败：" + e.getMessage());
        }
        
        return ResponseEntity.ok(response);
    }
    
    // 获取单个用户信息
    @GetMapping("/users/{id}")
    public ResponseEntity<Map<String, Object>> getUser(@PathVariable Long id, HttpSession session) {
        Map<String, Object> response = new HashMap<>();
        
        User currentUser = (User) session.getAttribute("currentUser");
        if (currentUser == null || !User.UserRole.ADMIN.equals(currentUser.getRole())) {
            response.put("success", false);
            response.put("message", "权限不足");
            return ResponseEntity.ok(response);
        }
        
        try {
            Optional<User> userOpt = userRepository.findById(id);
            if (!userOpt.isPresent()) {
                response.put("success", false);
                response.put("message", "用户不存在");
                return ResponseEntity.ok(response);
            }
            
            User user = userOpt.get();
            Map<String, Object> userData = new HashMap<>();
            userData.put("id", user.getId());
            userData.put("username", user.getUsername());
            userData.put("name", user.getName());
            userData.put("role", user.getRole().name());
            userData.put("contactInfo", user.getContactInfo());
            if (user.getCollege() != null) {
                Map<String, Object> collegeData = new HashMap<>();
                collegeData.put("id", user.getCollege().getId());
                collegeData.put("name", user.getCollege().getName());
                userData.put("college", collegeData);
            }
            
            response.put("success", true);
            response.putAll(userData);
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "获取用户信息失败：" + e.getMessage());
        }
        
        return ResponseEntity.ok(response);
    }
    
    // 更新用户信息
    @PutMapping("/users/{id}")
    public ResponseEntity<Map<String, Object>> updateUser(@PathVariable Long id,
                                                         @RequestParam String name,
                                                         @RequestParam String role,
                                                         @RequestParam(required = false) Long collegeId,
                                                         @RequestParam(required = false) String contactInfo,
                                                         HttpSession session) {
        Map<String, Object> response = new HashMap<>();
        
        User currentUser = (User) session.getAttribute("currentUser");
        if (currentUser == null || !User.UserRole.ADMIN.equals(currentUser.getRole())) {
            response.put("success", false);
            response.put("message", "权限不足");
            return ResponseEntity.ok(response);
        }
        
        // 检查是否试图修改自己的信息
        if (currentUser.getId().equals(id)) {
            response.put("success", false);
            response.put("message", "不能修改自己的信息");
            return ResponseEntity.ok(response);
        }
        
        try {
            Optional<User> userOpt = userRepository.findById(id);
            if (!userOpt.isPresent()) {
                response.put("success", false);
                response.put("message", "用户不存在");
                return ResponseEntity.ok(response);
            }
            
            User user = userOpt.get();
            user.setName(name);
            user.setRole(User.UserRole.valueOf(role));
            user.setContactInfo(contactInfo);
            
            if (collegeId != null) {
                Optional<College> collegeOpt = collegeRepository.findById(collegeId);
                if (collegeOpt.isPresent()) {
                    user.setCollege(collegeOpt.get());
                } else {
                    user.setCollege(null);
                }
            } else {
                user.setCollege(null);
            }
            
            userRepository.save(user);
            
            response.put("success", true);
            response.put("message", "用户信息更新成功");
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "更新失败：" + e.getMessage());
        }
        
        return ResponseEntity.ok(response);
    }
    
    // 删除用户
    @DeleteMapping("/users/{id}")
    public ResponseEntity<Map<String, Object>> deleteUser(@PathVariable Long id, HttpSession session) {
        Map<String, Object> response = new HashMap<>();
        
        User currentUser = (User) session.getAttribute("currentUser");
        if (currentUser == null || !User.UserRole.ADMIN.equals(currentUser.getRole())) {
            response.put("success", false);
            response.put("message", "权限不足");
            return ResponseEntity.ok(response);
        }
        
        // 检查是否试图删除自己
        if (currentUser.getId().equals(id)) {
            response.put("success", false);
            response.put("message", "不能删除自己的账户");
            return ResponseEntity.ok(response);
        }
        
        try {
            Optional<User> userOpt = userRepository.findById(id);
            if (!userOpt.isPresent()) {
                response.put("success", false);
                response.put("message", "用户不存在");
                return ResponseEntity.ok(response);
            }
            
            User user = userOpt.get();
            
            // 不能删除超级管理员
            if (User.UserRole.ADMIN.equals(user.getRole())) {
                response.put("success", false);
                response.put("message", "不能删除超级管理员账户");
                return ResponseEntity.ok(response);
            }
            
            userRepository.delete(user);
            
            response.put("success", true);
            response.put("message", "用户删除成功");
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "删除失败：" + e.getMessage());
        }
        
        return ResponseEntity.ok(response);
    }
    
    // 重置用户密码
    @PostMapping("/users/{id}/reset-password")
    public ResponseEntity<Map<String, Object>> resetUserPassword(@PathVariable Long id, HttpSession session) {
        Map<String, Object> response = new HashMap<>();
        
        User currentUser = (User) session.getAttribute("currentUser");
        if (currentUser == null || !User.UserRole.ADMIN.equals(currentUser.getRole())) {
            response.put("success", false);
            response.put("message", "权限不足");
            return ResponseEntity.ok(response);
        }
        
        // 检查是否试图重置自己的密码
        if (currentUser.getId().equals(id)) {
            response.put("success", false);
            response.put("message", "不能重置自己的密码");
            return ResponseEntity.ok(response);
        }
        
        try {
            Optional<User> userOpt = userRepository.findById(id);
            if (!userOpt.isPresent()) {
                response.put("success", false);
                response.put("message", "用户不存在");
                return ResponseEntity.ok(response);
            }
            
            User user = userOpt.get();
            // 重置为默认密码 123456
            user.setPassword("123456");
            userRepository.save(user);
            
            response.put("success", true);
            response.put("message", "密码重置成功，新密码为：123456");
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "重置失败：" + e.getMessage());
        }
        
        return ResponseEntity.ok(response);
    }
    
    // 管理员分配API
    @PostMapping("/assignments")
    public ResponseEntity<Map<String, Object>> assignManager(@RequestParam Long labId,
                                                            @RequestParam Long managerId,
                                                            HttpSession session) {
        Map<String, Object> response = new HashMap<>();
        
        User currentUser = (User) session.getAttribute("currentUser");
        if (currentUser == null || !User.UserRole.ADMIN.equals(currentUser.getRole())) {
            response.put("success", false);
            response.put("message", "权限不足");
            return ResponseEntity.ok(response);
        }
        
        try {
            Optional<Laboratory> labOpt = laboratoryRepository.findById(labId);
            Optional<User> managerOpt = userRepository.findById(managerId);
            
            if (labOpt.isPresent() && managerOpt.isPresent()) {
                Laboratory laboratory = labOpt.get();
                User manager = managerOpt.get();
                
                // 检查用户是否是实验室管理员
                if (!User.UserRole.LAB_MANAGER.equals(manager.getRole())) {
                    response.put("success", false);
                    response.put("message", "只能分配实验室管理员角色的用户");
                    return ResponseEntity.ok(response);
                }
                
                // 检查是否已经分配了该管理员
                if (laboratory.getManagers() != null && laboratory.getManagers().contains(manager)) {
                    response.put("success", false);
                    response.put("message", "该管理员已经分配给此实验室");
                    return ResponseEntity.ok(response);
                }
                
                // 初始化管理员列表（如果为空）
                if (laboratory.getManagers() == null) {
                    laboratory.setManagers(new java.util.ArrayList<>());
                }
                
                // 初始化用户的实验室列表（如果为空）
                if (manager.getLaboratories() == null) {
                    manager.setLaboratories(new java.util.ArrayList<>());
                }
                
                // 添加关联关系
                laboratory.getManagers().add(manager);
                manager.getLaboratories().add(laboratory);
                
                // 保存
                laboratoryRepository.save(laboratory);
                userRepository.save(manager);
                
                response.put("success", true);
                response.put("message", "管理员分配成功");
            } else {
                response.put("success", false);
                response.put("message", "实验室或管理员不存在");
            }
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "分配失败：" + e.getMessage());
        }
        
        return ResponseEntity.ok(response);
    }
    
    @DeleteMapping("/assignments/{labId}")
    public ResponseEntity<Map<String, Object>> removeManagerAssignment(@PathVariable Long labId,
                                                                      HttpSession session) {
        Map<String, Object> response = new HashMap<>();
        
        User currentUser = (User) session.getAttribute("currentUser");
        if (currentUser == null || !User.UserRole.ADMIN.equals(currentUser.getRole())) {
            response.put("success", false);
            response.put("message", "权限不足");
            return ResponseEntity.ok(response);
        }
        
        try {
            Optional<Laboratory> labOpt = laboratoryRepository.findById(labId);
            
            if (labOpt.isPresent()) {
                Laboratory laboratory = labOpt.get();
                
                if (laboratory.getManagers() != null && !laboratory.getManagers().isEmpty()) {
                    // 移除所有管理员分配
                    for (User manager : laboratory.getManagers()) {
                        if (manager.getLaboratories() != null) {
                            manager.getLaboratories().remove(laboratory);
                            userRepository.save(manager);
                        }
                    }
                    
                    laboratory.getManagers().clear();
                    laboratoryRepository.save(laboratory);
                    
                    response.put("success", true);
                    response.put("message", "管理员分配移除成功");
                } else {
                    response.put("success", false);
                    response.put("message", "该实验室没有分配管理员");
                }
            } else {
                response.put("success", false);
                response.put("message", "实验室不存在");
            }
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "移除失败：" + e.getMessage());
        }
        
        return ResponseEntity.ok(response);
    }
    
    // 安全检查API
    @PostMapping("/safety-check")
    public ResponseEntity<Map<String, Object>> createSafetyCheck(@RequestParam Long termId,
                                                                @RequestParam Long laboratoryId,
                                                                @RequestParam String checkDate,
                                                                @RequestParam String window,
                                                                @RequestParam String circuit,
                                                                @RequestParam String fire,
                                                                @RequestParam String equipment,
                                                                @RequestParam String items,
                                                                @RequestParam String hygiene,
                                                                @RequestParam String overall,
                                                                @RequestParam(required = false) String otherIssues,
                                                                HttpSession session) {
        Map<String, Object> response = new HashMap<>();
        
        User currentUser = (User) session.getAttribute("currentUser");
        if (currentUser == null) {
            response.put("success", false);
            response.put("message", "用户未登录");
            return ResponseEntity.ok(response);
        }
        
        try {
            Optional<Term> termOpt = termRepository.findById(termId);
            Optional<Laboratory> labOpt = laboratoryRepository.findById(laboratoryId);
            
            if (!termOpt.isPresent() || !labOpt.isPresent()) {
                response.put("success", false);
                response.put("message", "学期或实验室不存在");
                return ResponseEntity.ok(response);
            }
            
            // 检查该用户在该实验室该日期是否已有记录
            LocalDate date = LocalDate.parse(checkDate);
            List<SafetyCheck> existingRecords = safetyCheckRepository.findByUserAndLaboratoryAndCheckDate(
                currentUser, labOpt.get(), date);
            
            if (!existingRecords.isEmpty()) {
                response.put("success", false);
                response.put("message", "您已在 " + checkDate + " 对该实验室进行过安全检查，不能重复提交");
                return ResponseEntity.ok(response);
            }
            
            // 创建安全检查记录
            SafetyCheck safetyCheck = new SafetyCheck();
            safetyCheck.setTerm(termOpt.get());
            safetyCheck.setLaboratory(labOpt.get());
            safetyCheck.setUser(currentUser);
            safetyCheck.setCheckDate(LocalDate.parse(checkDate));
            safetyCheck.setCheckerName(currentUser.getName());
            
            // 设置检查状态
            safetyCheck.setWindowStatus(SafetyCheck.CheckStatus.valueOf(window.toUpperCase()));
            safetyCheck.setCircuitStatus(SafetyCheck.CheckStatus.valueOf(circuit.toUpperCase()));
            safetyCheck.setFireStatus(SafetyCheck.CheckStatus.valueOf(fire.toUpperCase()));
            safetyCheck.setEquipmentStatus(SafetyCheck.CheckStatus.valueOf(equipment.toUpperCase()));
            safetyCheck.setItemsStatus(SafetyCheck.CheckStatus.valueOf(items.toUpperCase()));
            safetyCheck.setHygieneStatus(SafetyCheck.CheckStatus.valueOf(hygiene.toUpperCase()));
            
            // 设置总体状态
            safetyCheck.setOverallStatus(SafetyCheck.OverallStatus.valueOf(overall.toUpperCase()));
            
            // 设置其他问题
            if (otherIssues != null && !otherIssues.trim().isEmpty()) {
                safetyCheck.setRemark(otherIssues.trim());
            }
            
            // 设置处理状态
            safetyCheck.setHandleStatus(SafetyCheck.HandleStatus.PENDING);
            safetyCheck.setCreateTime(LocalDateTime.now());
            
            safetyCheckRepository.save(safetyCheck);
            
            response.put("success", true);
            response.put("message", "安全检查记录提交成功");
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "提交失败：" + e.getMessage());
        }
        
        return ResponseEntity.ok(response);
    }
    
    // 检查是否存在重复的安全检查记录
    @GetMapping("/safety-check/exists")
    public ResponseEntity<Map<String, Object>> checkSafetyCheckExists(@RequestParam Long laboratoryId,
                                                                     @RequestParam String checkDate,
                                                                     HttpSession session) {
        Map<String, Object> response = new HashMap<>();
        
        User currentUser = (User) session.getAttribute("currentUser");
        if (currentUser == null) {
            response.put("success", false);
            response.put("message", "用户未登录");
            return ResponseEntity.ok(response);
        }
        
        try {
            Optional<Laboratory> labOpt = laboratoryRepository.findById(laboratoryId);
            if (!labOpt.isPresent()) {
                response.put("success", false);
                response.put("message", "实验室不存在");
                return ResponseEntity.ok(response);
            }
            
            LocalDate date = LocalDate.parse(checkDate);
            List<SafetyCheck> existingRecords = safetyCheckRepository.findByUserAndLaboratoryAndCheckDate(
                currentUser, labOpt.get(), date);
            
            response.put("success", true);
            response.put("exists", !existingRecords.isEmpty());
            if (!existingRecords.isEmpty()) {
                response.put("message", "您已在 " + checkDate + " 对该实验室进行过安全检查");
            }
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "检查失败：" + e.getMessage());
        }
        
        return ResponseEntity.ok(response);
    }
    
    // 获取安全检查记录API
    @GetMapping("/safety-records")
    public ResponseEntity<?> getSafetyRecords(@RequestParam(required = false) Long termId,
                                             @RequestParam(required = false) Long laboratoryId,
                                             @RequestParam(required = false) String status,
                                             @RequestParam(required = false) String startDate,
                                             @RequestParam(required = false) String endDate,
                                             HttpSession session) {
        User currentUser = (User) session.getAttribute("currentUser");
        if (currentUser == null) {
            return ResponseEntity.ok(new HashMap<String, Object>() {{
                put("success", false);
                put("message", "用户未登录");
            }});
        }
        
        try {
            List<SafetyCheck> records;
            
            // 根据用户角色获取记录
            if (User.UserRole.ADMIN.equals(currentUser.getRole())) {
                // 超级管理员可以查看所有记录
                records = safetyCheckRepository.findAll();
            } else {
                // 实验室管理员只能查看自己管理的实验室记录
                records = safetyCheckRepository.findByUser(currentUser);
            }
            
            // 应用过滤条件
            if (termId != null) {
                records = records.stream()
                    .filter(record -> record.getTerm().getId().equals(termId))
                    .toList();
            }
            
            if (laboratoryId != null) {
                records = records.stream()
                    .filter(record -> record.getLaboratory().getId().equals(laboratoryId))
                    .toList();
            }
            
            if (status != null && !status.isEmpty()) {
                records = records.stream()
                    .filter(record -> record.getOverallStatus().name().toLowerCase().equals(status.toLowerCase()))
                    .toList();
            }
            
            if (startDate != null && !startDate.isEmpty()) {
                LocalDate start = LocalDate.parse(startDate);
                records = records.stream()
                    .filter(record -> !record.getCheckDate().isBefore(start))
                    .toList();
            }
            
            if (endDate != null && !endDate.isEmpty()) {
                LocalDate end = LocalDate.parse(endDate);
                records = records.stream()
                    .filter(record -> !record.getCheckDate().isAfter(end))
                    .toList();
            }
            
            // 转换为前端需要的格式
            var result = records.stream().map(record -> {
                Map<String, Object> recordMap = new HashMap<>();
                recordMap.put("id", record.getId());
                recordMap.put("date", record.getCheckDate().toString());
                recordMap.put("term", record.getTerm().getName());
                recordMap.put("laboratory", record.getLaboratory().getName());
                recordMap.put("checker", record.getCheckerName());
                recordMap.put("status", record.getOverallStatus().name().toLowerCase());
                recordMap.put("handleStatus", record.getHandleStatus() != null ? record.getHandleStatus().name() : "PENDING");
                recordMap.put("handleTime", record.getHandleTime() != null ? record.getHandleTime().toString() : null);
                
                // 检查详情
                Map<String, String> details = new HashMap<>();
                details.put("window", record.getWindowStatus() == SafetyCheck.CheckStatus.OK ? "ok" : "problem");
                details.put("circuit", record.getCircuitStatus() == SafetyCheck.CheckStatus.OK ? "ok" : "problem");
                details.put("fire", record.getFireStatus() == SafetyCheck.CheckStatus.OK ? "ok" : "problem");
                details.put("equipment", record.getEquipmentStatus() == SafetyCheck.CheckStatus.OK ? "ok" : "problem");
                details.put("items", record.getItemsStatus() == SafetyCheck.CheckStatus.OK ? "ok" : "problem");
                details.put("hygiene", record.getHygieneStatus() == SafetyCheck.CheckStatus.OK ? "ok" : "problem");
                recordMap.put("details", details);
                
                recordMap.put("otherIssues", record.getRemark() != null ? record.getRemark() : "");
                
                return recordMap;
            }).toList();
            
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            return ResponseEntity.ok(new HashMap<String, Object>() {{
                put("success", false);
                put("message", "获取记录失败：" + e.getMessage());
            }});
        }
    }
    
    // 标记安全检查记录为已处理
    @PostMapping("/safety-records/{id}/handle")
    public ResponseEntity<Map<String, Object>> markSafetyCheckAsHandled(@PathVariable Long id, HttpSession session) {
        Map<String, Object> response = new HashMap<>();
        
        User currentUser = (User) session.getAttribute("currentUser");
        if (currentUser == null) {
            response.put("success", false);
            response.put("message", "用户未登录");
            return ResponseEntity.ok(response);
        }
        
        try {
            Optional<SafetyCheck> recordOpt = safetyCheckRepository.findById(id);
            if (!recordOpt.isPresent()) {
                response.put("success", false);
                response.put("message", "记录不存在");
                return ResponseEntity.ok(response);
            }
            
            SafetyCheck record = recordOpt.get();
            
            // 检查权限：只能处理自己的记录或管理员可以处理所有记录
            if (!User.UserRole.ADMIN.equals(currentUser.getRole()) && 
                !record.getUser().getId().equals(currentUser.getId())) {
                response.put("success", false);
                response.put("message", "权限不足");
                return ResponseEntity.ok(response);
            }
            
            // 只有异常记录才能标记为已处理
            if (record.getOverallStatus() != SafetyCheck.OverallStatus.ABNORMAL) {
                response.put("success", false);
                response.put("message", "只有异常记录才能标记为已处理");
                return ResponseEntity.ok(response);
            }
            
            // 更新处理状态
            record.setHandleStatus(SafetyCheck.HandleStatus.HANDLED);
            record.setHandleTime(LocalDateTime.now());
            safetyCheckRepository.save(record);
            
            response.put("success", true);
            response.put("message", "已成功标记为已处理");
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "标记失败：" + e.getMessage());
        }
        
        return ResponseEntity.ok(response);
    }
    
    // 导出单条记录为Excel
    @GetMapping("/safety-records/{id}/export")
    public void exportSingleRecord(@PathVariable Long id, HttpSession session, HttpServletResponse response) throws IOException {
        User currentUser = (User) session.getAttribute("currentUser");
        if (currentUser == null) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            response.getWriter().write("用户未登录");
            return;
        }
        
        try {
            Optional<SafetyCheck> recordOpt = safetyCheckRepository.findById(id);
            if (!recordOpt.isPresent()) {
                response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
                response.getWriter().write("记录不存在");
                return;
            }
            
            SafetyCheck record = recordOpt.get();
            
            // 检查权限
            if (!User.UserRole.ADMIN.equals(currentUser.getRole()) && 
                !record.getUser().getId().equals(currentUser.getId())) {
                response.setStatus(HttpServletResponse.SC_FORBIDDEN);
                response.getWriter().write("权限不足");
                return;
            }
            
            // 转换为导出DTO
            SafetyCheckExportDTO exportDto = convertToExportDTO(record);
            List<SafetyCheckExportDTO> dataList = Arrays.asList(exportDto);
            
            // 设置响应头
            String fileName = "安全检查记录_" + record.getLaboratory().getName() + "_" + record.getCheckDate() + ".xlsx";
            String encodedFileName = URLEncoder.encode(fileName, StandardCharsets.UTF_8);
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setCharacterEncoding("utf-8");
            response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + encodedFileName);
            
            // 使用EasyExcel写入
            EasyExcel.write(response.getOutputStream(), SafetyCheckExportDTO.class)
                    .sheet("安全检查记录")
                    .doWrite(dataList);
            
        } catch (Exception e) {
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            response.getWriter().write("导出失败：" + e.getMessage());
        }
    }
    
    // 批量导出记录为Excel
    @GetMapping("/safety-records/export")
    public void exportRecords(@RequestParam(required = false) Long termId,
                             @RequestParam(required = false) Long laboratoryId,
                             @RequestParam(required = false) String status,
                             @RequestParam(required = false) String startDate,
                             @RequestParam(required = false) String endDate,
                             HttpSession session,
                             HttpServletResponse response) throws IOException {
        User currentUser = (User) session.getAttribute("currentUser");
        if (currentUser == null) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            response.getWriter().write("用户未登录");
            return;
        }
        
        try {
            List<SafetyCheck> records;
            
            // 根据用户角色获取记录
            if (User.UserRole.ADMIN.equals(currentUser.getRole())) {
                records = safetyCheckRepository.findAll();
            } else {
                records = safetyCheckRepository.findByUser(currentUser);
            }
            
            // 应用过滤条件（与查询API相同的逻辑）
            if (termId != null) {
                records = records.stream()
                    .filter(record -> record.getTerm().getId().equals(termId))
                    .toList();
            }
            
            if (laboratoryId != null) {
                records = records.stream()
                    .filter(record -> record.getLaboratory().getId().equals(laboratoryId))
                    .toList();
            }
            
            if (status != null && !status.isEmpty()) {
                records = records.stream()
                    .filter(record -> record.getOverallStatus().name().toLowerCase().equals(status.toLowerCase()))
                    .toList();
            }
            
            if (startDate != null && !startDate.isEmpty()) {
                LocalDate start = LocalDate.parse(startDate);
                records = records.stream()
                    .filter(record -> !record.getCheckDate().isBefore(start))
                    .toList();
            }
            
            if (endDate != null && !endDate.isEmpty()) {
                LocalDate end = LocalDate.parse(endDate);
                records = records.stream()
                    .filter(record -> !record.getCheckDate().isAfter(end))
                    .toList();
            }
            
            // 转换为导出DTO列表
            List<SafetyCheckExportDTO> exportData = records.stream()
                    .map(this::convertToExportDTO)
                    .toList();
            
            // 设置响应头
            String fileName = "安全检查记录_" + LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMdd_HHmmss")) + ".xlsx";
            String encodedFileName = URLEncoder.encode(fileName, StandardCharsets.UTF_8);
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setCharacterEncoding("utf-8");
            response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + encodedFileName);
            
            // 使用EasyExcel写入
            EasyExcel.write(response.getOutputStream(), SafetyCheckExportDTO.class)
                    .sheet("安全检查记录")
                    .doWrite(exportData);
            
        } catch (Exception e) {
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            response.getWriter().write("导出失败：" + e.getMessage());
        }
    }
    
    // 转换SafetyCheck为导出DTO的辅助方法
    private SafetyCheckExportDTO convertToExportDTO(SafetyCheck record) {
        String handleTime = "";
        if (record.getOverallStatus() == SafetyCheck.OverallStatus.NORMAL) {
            // 正常记录显示检查日期
            handleTime = record.getCheckDate().toString();
        } else if (record.getHandleTime() != null) {
            // 异常已处理记录显示处理时间
            handleTime = record.getHandleTime().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm"));
        } else {
            // 异常待处理记录显示"-"
            handleTime = "-";
        }
        
        return new SafetyCheckExportDTO(
            record.getCheckDate().toString(),
            record.getTerm().getName(),
            record.getLaboratory().getName(),
            record.getCheckerName(),
            record.getWindowStatus() == SafetyCheck.CheckStatus.OK ? "正常" : "异常",
            record.getCircuitStatus() == SafetyCheck.CheckStatus.OK ? "正常" : "异常",
            record.getFireStatus() == SafetyCheck.CheckStatus.OK ? "正常" : "异常",
            record.getEquipmentStatus() == SafetyCheck.CheckStatus.OK ? "正常" : "异常",
            record.getItemsStatus() == SafetyCheck.CheckStatus.OK ? "正常" : "异常",
            record.getHygieneStatus() == SafetyCheck.CheckStatus.OK ? "正常" : "异常",
            record.getOverallStatus() == SafetyCheck.OverallStatus.NORMAL ? "正常" : "异常",
            record.getOverallStatus() == SafetyCheck.OverallStatus.NORMAL ? "已处理" : 
                (record.getHandleStatus() == SafetyCheck.HandleStatus.HANDLED ? "已处理" : "待处理"),
            handleTime,
            record.getRemark() != null ? record.getRemark() : ""
        );
    }
} 